<template>
    <view class="page-container">
        <view class="form-group">
            <view class="form-group__label">地址</view>
            <wd-cell is-link @click="handleShowPaymentPopup" :value="userInfo||'请选择地址'">
            </wd-cell>
        </view>
        
        <view class="form-group">
            <view class="form-group__label">预约时间</view>
            <wd-datetime-picker v-model="dateTimeValue" :formatter="formatDatetime" />
        </view>
      <CartListView
        ref="cartListRef"
        :cart-data="cartCategories"
        @update:cart-data="handleCartDataUpdate"
        @total-change="handleTotalChange"
        @checkout="handleCheckout"
      />
   

    </view>

    <!-- 页面标题栏 -->

    <view class="payment-popup">
        <wd-action-sheet title="预约地址" v-model="showBottomModel" @close="handleHidePaymentPopup">
            <view class="address-delivery-page">

                <view v-if="dialogState==2 || dialogState==3" class="edit_view">
                    <wd-form ref="form" :model="model">
                        <wd-cell-group border>
                            <wd-input label="用户名" label-width="100px" prop="value1" clearable v-model="formData.name"
                                placeholder="请输入用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
                            <wd-input label="手机号" label-width="100px" prop="value1" clearable v-model="formData.phone"
                                placeholder="请输入手机号" :rules="[{ required: true, message: '请填写用户名' }]" />
                            <wd-textarea 
                                  v-model="formData.detailAddress"
                            label="地址" placeholder="请输入地址信息" clearable prop="content" type="textarea"
                                label-width="100px"  :rules="[{ required: true, message: '请填写用户名' }]" />



                        </wd-cell-group>
                        <view class="footer">
                            <wd-button @click="dialogAction(1,{})">返回</wd-button>
                            <wd-button type="primary"  @click="handleSubmit" >提交</wd-button>
                        </view>
                    </wd-form>
                </view>
                <!--end  edit_view -->

                <!-- 主体内容区 -->
                <view v-if="dialogState==1" class="content-container">
                    <!-- 第一行：常用地址管理栏 -->
                    <view class="address-header">
                        <view class="header-title">常用地址</view>
                        <view class="header-actions">

                            <wd-button type="primary" size="small" @click="dialogAction(2,null)">
                                新增地址
                            </wd-button>
                        </view>
                    </view>

                    <!-- 第二行：地址列表 -->
                    <view class="address-list">
                        <!-- 地址为空状态 -->
                        <view v-if="addressList.length === 0" class="empty-address">
                            <image src="/static/icons/empty-address.png" class="empty-icon" mode="widthFix"></image>
                            <view class="empty-text">暂无保存的地址</view>
                            <wd-button type="primary" size="small" class="empty-add-btn">
                                立即添加
                            </wd-button>
                        </view>

                        <!-- 地址列表项 -->
                        <view v-for="(item, index) in addressList" :key="index" class="address-item">
                            <!-- 地址信息列（第一列） -->
                            <view class="address-info" @click="getCurrentInfo(item)">
                                <view class="address-detail">{{ item.detailAddress }}</view>
                                <view class="address-contact">
                                    <text class="contact-name">{{ item.name }}</text>
                                    <text class="contact-phone">{{ item.phone }}</text>
                                </view>
                            </view>

                            <!-- 编辑按钮列（第二列） -->
                            <view class="address-action">
                                <wd-button type="text" text-color="#ff4d4f" size="small" @click="dialogAction(3,item)">
                                    编辑
                                </wd-button>
                                <wd-button type="text" text-color="#ff4d4f" size="small" class="action-btn">
                                    删除
                                </wd-button>
                            </view>
                        </view>
                    </view>
                </view>
                <!--end content-container -->


            </view>
        </wd-action-sheet>
    </view>
 

     <!-- 底部操作栏（可选，根据需求添加） -->
      <view class="bottom-nav" v-if="!showBottomModel && !isFilterPopupOpen">
      <view class="bottom-nav__price">
        <view class="price__content">
          <text class="price__symbol">¥</text>
          <text class="price__amount">{{ currentTotalAmount }}</text>
        </view>
        <view class="price__desc">合计（仅勾选商品）：</view>
      </view>
      <view class="bottom-nav__reserve">
        <wd-button  type="error" size="medium" class="reserve__btn" :disabled="cartCount === 0">
          立即预约
        </wd-button>
      </view>
    </view>

    <!-- <view class="bottom-bar">

           <view class="cart-summary">
                <view class="summary-info">
                    <text class="total-text">合计（仅勾选商品）：</text>
                    <text class="total-price">￥{{ currentTotalAmount }}</text>
                </view>
                <wd-button type="primary" class="checkout-btn"  @click="handleCheckout">
                    结算
                </wd-button>
            </view>

   
      
    </view> -->

</template>

<script setup lang="ts">
import { ref, reactive ,nextTick} from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import { useToast } from 'wot-design-uni'
import CartListView from '@/components/CartDetailList/index.vue'

const userInfo=ref("")

const showBottomModel = ref(false);
const cartCategories=ref([])
// 1. 新增删除相关响应式变量
const dialogState=ref(1);//1 显示content，2 显示添加，3显示编辑
// 父组件存储合计金额的响应式变量
const currentTotalAmount = ref('0.00')
// 购物车事件
const handleCartDataUpdate = (newData) => {
  cartCategories.value = newData
}
const handleTotalChange = (amount: string) => {
  currentTotalAmount.value = amount
}

const handleCheckout = (selectedCartData) => {
}
const handleShowPaymentPopup = () => {
    showBottomModel.value = true
}

const handleHidePaymentPopup = () => {
    dialogState.value=1;
    showBottomModel.value = false
}

const getCurrentInfo=(item)=>{
    console.log("item:",item)
    userInfo.value=`${item.detailAddress} , ${item.name} , ${item.phone}`
    handleHidePaymentPopup();
}

// 时间选择器相关
const dateTimeValue = ref(Date.now())
const formatDatetime = (type, value) => {
	switch (type) {
		case 'year':
			return value + '年'
		case 'month':
			return value + '月'
		case 'date':
			return value + '日'
		case 'hour':
			return value + '时'
		case 'minute':
			return value + '分'
		default:
			return value
	}
}

// 页面基础配置
const { success: showSuccess } = useToast()

const model = reactive({
    value1: '',
    value2: ''
})

const form = ref()

function handleSubmit() {
    form.value
        .validate()
        .then(({ valid, errors }) => {
            if (valid) {
                showSuccess({
                    msg: '校验通过'
                })
            }
        })
        .catch((error) => {
            console.log(error, 'error')
        })
}


// 地址列表数据（模拟）
const addressList = ref([
    {
        name: "张三",
        phone: "13800138000",
        detailAddress: "北京市朝阳区建国路88号现代城SOHO A座2301室"
    },
    {
        name: "李四",
        phone: "13900139000",
        detailAddress: "上海市浦东新区张江高科技园区博云路2号浦软大厦10层"
    }
])

// 弹窗状态与表单数据
const formData = reactive({
    name: "",
    phone: "",
    detailAddress: ""
})

// 子组件引用
const cartListRef = ref(null)

// 页面加载
onLoad(async () => {
  const value = uni.getStorageSync('cartCategories_data')
  if (value) {
    cartCategories.value = JSON.parse(value)
  }

  // 等待 DOM 更新后获取初始金额
  await nextTick()
//   cartListRef.value?.selectAll()
  if (cartListRef.value && typeof cartListRef.value.getCartTotalAmount === 'function') {
    currentTotalAmount.value = cartListRef.value.getCartTotalAmount()
  }
 if (cartListRef.value && typeof cartListRef.value.setDefaultSelectAll === 'function') {
cartListRef.value.setDefaultSelectAll()
  }
  
})



const dialogAction=(num,item)=>{
    if(num==3){
        formData.phone=item.phone;
         formData.detailAddress=item.detailAddress;
          formData.name=item.name;
    }
    dialogState.value=num
}


</script>

<style lang="less" scoped>
@import url("@/static/styles/family/onlineSupermarket/bottom-nav.less");



/* 页面整体样式 */
.address-delivery-page {
    background-color: #f5f5f7;
    min-height: 100vh;
}

/* 内容容器：控制左右间距与上下内边距 */
.content-container {
    padding: 20rpx 30rpx;
}

/* 第一行：常用地址管理栏 */
.address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0;
    margin-bottom: 10rpx;

    .header-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #1d1d1f;
    }

    .header-actions {
        display: flex;
        gap: 16rpx;

        /deep/ .wd-button {
            padding: 0 20rpx;
            height: 56rpx;
            line-height: 56rpx;
            font-size: 26rpx;
        }

        /deep/ .wd-button--text {
            color: #333;
        }
    }
}

/* 第二行：地址列表 */
.address-list {
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
}

/* 地址为空状态 */
.empty-address {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80rpx 20rpx;

    .empty-icon {
        width: 180rpx;
        margin-bottom: 30rpx;
        opacity: 0.5;
    }

    .empty-text {
        font-size: 28rpx;
        color: #86868b;
        margin-bottom: 40rpx;
    }

    .empty-add-btn {
        width: 200rpx;
        height: 64rpx;
        line-height: 64rpx;
        font-size: 28rpx;
    }
}

/* 地址列表项 */
.address-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 28rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f7;

    &:last-child {
        border-bottom: none;
    }

    .address-action {
        display: flex;
        flex-direction: column; // 纵向排列编辑/删除按钮
        gap: 16rpx; // 按钮之间间距
        padding-top: 4rpx;

        // 单个操作按钮样式
        .action-btn {
            padding: 0 !important; // 清除默认内边距
            font-size: 24rpx !important; // 缩小字体，避免占用过多空间
            height: auto !important; // 取消固定高度
            line-height: normal !important;
        }
    }

    // 地址信息列（第一列）
    .address-info {
        flex: 1;
        margin-right: 20rpx;

        .address-detail {
            font-size: 28rpx;
            color: #1d1d1f;
            line-height: 40rpx;
            margin-bottom: 12rpx;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .address-contact {
            display: flex;
            gap: 24rpx;
            font-size: 26rpx;
            color: #86868b;

            .contact-name {
                white-space: nowrap;
            }

            .contact-phone {
                white-space: nowrap;
            }
        }
    }

    // 编辑按钮列（第二列）
    .address-action {
        padding-top: 4rpx; // 微调垂直对齐

        /deep/ .wd-button {
            padding: 0;
            font-size: 26rpx;
            color: #ff4d4f;
        }
    }

    // 点击反馈
    &:active {
        background-color: rgba(0, 0, 0, 0.02);
    }
}

/* 新增/编辑地址弹窗表单 */
.address-form {
    padding: 10rpx 0 20rpx;

    .form-item {
        margin-bottom: 36rpx;

        .form-label {
            display: block;
            margin-bottom: 12rpx;
            font-size: 26rpx;
            color: #1d1d1f;

            &.required::before {
                content: "*";
                color: #ff4d4f;
                margin-right: 6rpx;
            }
        }

        /deep/ .wd-input {
            height: 68rpx;
            font-size: 26rpx;
            border-radius: 12rpx;
            background-color: #f5f5f7;
        }
    }

    .form-buttons {
        display: flex;
        gap: 20rpx;
        margin-top: 40rpx;

        /deep/ .wd-button {
            flex: 1;
            height: 68rpx;
            line-height: 68rpx;
            font-size: 28rpx;
        }
    }
}

.payment-popup {
    position: relative;

    :deep(.wd-popup) {
        height: 80% !important;
    }
}

.page-container {
    padding: 24rpx;
    background-color: #f8f8f8;
    min-height: 100vh;
    box-sizing: border-box;
}

.form-group {
    display: flex;
    align-items: center;
    // margin-bottom: 32rpx;
    background: #ffffff;
    overflow: hidden;
    padding: 4rpx 22rpx;

    &__label {
        flex-shrink: 0;
        width: 160rpx; // 固定标签宽度，可根据需要调整
        font-size: 28rpx;
        font-weight: 600;
        color: #333333;
        line-height: 1.4;
        margin-right: 24rpx;
    }
}

// 单元格样式调整 - 占据剩余空间
.wd-cell {
    flex: 1;

    ::v-deep .wd-cell__value {
        color: #999999;
        font-size: 28rpx;
    }

    ::v-deep .wd-cell--active {
        background-color: transparent;
    }
}

// 日期时间选择器样式调整 - 占据剩余空间
.wd-datetime-picker {
    flex: 1;

    ::v-deep .wd-picker {
        background: #f5f5f5;
        border-radius: 12rpx;
        padding: 20rpx 24rpx;

        .wd-picker__value {
            color: #333333;
            font-size: 28rpx;
        }

        .wd-picker__placeholder {
            color: #999999;
            font-size: 28rpx;
        }
    }
}
.footer{
    display: flex;
        justify-content: space-evenly;
    background: #fff;
    padding-bottom: 30px;
}

// 底部操作栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .total-info {
    .total-label {
      font-size: 26rpx;
      color: #666;
    }
    .total-count {
      font-size: 28rpx;
      font-weight: 500;
      color: #ff4d4f;
      margin-left: 8rpx;
    }
  }

  .operate-btns {
    display: flex;
    gap: 20rpx;

    /deep/ .wd-button {
      width: 180rpx;
      height: 68rpx;
      line-height: 68rpx;
      font-size: 28rpx;
    }
  }
}


/* 合计栏样式 */
.cart-summary {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-radius: 16rpx;

  .summary-info {
    .total-text {
      font-size: 28rpx;
      color: #666;
    }

    .total-price {
      font-size: 32rpx;
      color: #ff4d4f;
      font-weight: 500;
      margin-left: 8rpx;
    }
  }

  .checkout-btn {
    width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
  }
}
</style>